package com.keyidea.jfxui.portal.util.filelock;

import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

@Slf4j
public class FileLockUtil {
    /**
     * 文件锁，确保每次只能启动一个程序
     */
    public static void lockByFile(Class clazz, String[] args, String fileName, FileLockFunctional fileLockFunctional) {
        try {
            File file = new File(fileName);
            if (!file.exists()) {
                boolean isCreate = file.createNewFile();
                if (!isCreate) {
                    log.error("创建文件{}失败", fileName);
                }
            }
            try (RandomAccessFile raf = new RandomAccessFile(file, "rw");
                 FileChannel channel = raf.getChannel();
                 FileLock lock = channel.tryLock()) {
                if (lock == null) {
                    JOptionPane.showMessageDialog(null, "同文件夹下已启动一个程序！");
                    System.exit(0);
                } else {
                    // 加载主程序
                    fileLockFunctional.handle(clazz, args);
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
}
